package com.example.blog.service.impl;

import com.example.blog.entity.User;
import com.example.blog.mapper.UserMapper;
import com.example.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;



    @Override
    public User registerUser(String username, String email, String password) {
        // 检查用户名和邮箱是否已存在
        if (userMapper.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        if (userMapper.existsByEmail(email)) {
            throw new RuntimeException("邮箱已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(password); // 注意：实际应用中应加密密码，但当前未集成安全框架

        userMapper.insert(user);
        return user;
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + username));
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.selectByEmail(email)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + email));
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    @Override
    public boolean existsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }

    @Override
    public User updateUser(User user) {
        userMapper.update(user);
        return user;
    }

    @Override
    public User findById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
        return user;
    }

}